package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张杰
 * Date: 2022-04-21
 * Time: 19:24
 */
public class UdpEchoClient {
    // 站在客户端的角度
    // 源 IP:本机IP
    // 源端口: 系统分配的端口
    // 目的IP: 服务器的IP
    // 目的端口:  服务器的端口
    // 协议类型: UDP
    private DatagramSocket socket = null;
    private String serverIP;
    private int serverPort;

    public UdpEchoClient(String ip,int port) throws SocketException {
        //此处的port是服务器的端口
        //客户端启动的时候,不需要给socket指定端口,客户端自己的端口是系统随机分配的
        socket = new DatagramSocket();//不指定端口号,系统就会自行匹配端口号
        serverIP = ip;
        serverPort = port;
    }

    public void start() throws IOException {
        Scanner sc = new Scanner(System.in);
        while(true) {
            //1.从控制台读取用户输入的字符串
            System.out.print("-> ");
            String request = sc.next();
            //2.把这个用户输入的内容,构造成一个UDP请求,并发送
            //  构造的请求包里面有两部分内容:
            //  1) 数据的内容: request字符串
            //  2) 数据要发给谁 服务器的IP + 端口
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.length(),
                    InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);
            //3.从服务器读取相应数据,并解析
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength(),"UTF-8");
            //4.把相应结果显示到控制台上.
            System.out.printf("req: %s, resp: %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
